# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class OrangePipeline:

    def open_spider(self, spider):
        self.fp = open('oe.json', 'a', encoding='utf-8')

    def process_item(self, item, spider):
        # 操作太频繁
        # with open('zz.json', 'a', encoding='utf-8')as fp:
        #     fp.write(str(item))

        self.fp.write(str(item))
        return item

    def close_spider(self, spider):
        self.fp.close()


import pymysql

from scrapy.utils.project import get_project_settings

class OrangeMysqlPipeline:
    def __init__(self):
        self.cursor = None
        self.conn = None
#
    def open_spider(self, spider):

        # DB_HOST = '192.168.45.58'
        # DB_PORT = 3306
        # DB_USER = 'root'
        # DB_PASSWORD = 'mysql'
        # DB_NAME = 'fruit'
        # DB_CHARSET = 'utf8'

        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.name = settings['DB_NAME']
        self.charset = settings['DB_CHARSET']

        self.connect()
    def connect(self):

        self.conn = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            password='mysql',
            database='fruit'
        )
        self.cursor = self.conn.cursor()
#
    def process_item(self, item, spider):
        # sql = 'insert into zzsj(title,href) values("{}","{}")'.fromat(item['title'], item['href'])
        # self.cursor.execute(sql)
        sql = 'INSERT INTO method(title, href) VALUES (%s, %s)'
        self.cursor.execute(sql, (item['title'], item['href']))
        self.conn.commit()
        return item
#
    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()